package com.vcourse.service.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vcourse.commons.result.ResultCodeEnum;
import com.vcourse.commons.utils.FormUtils;
import com.vcourse.commons.utils.JwtInfo;
import com.vcourse.commons.utils.JwtUtils;
import com.vcourse.commons.utils.MD5;
import com.vcourse.service.base.dto.MemberDto;
import com.vcourse.service.base.exception.CustomException;
import com.vcourse.service.base.service.RedisService;
import com.vcourse.service.user.entity.Member;
import com.vcourse.service.user.mapper.MemberMapper;
import com.vcourse.service.user.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vcourse.service.user.vo.LoginVo;
import com.vcourse.service.user.vo.RegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Zengsh123
 * @since 2020-06-08
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    @Resource
    private RedisService redisService;
    @Value("redis.database")
    private String REDIS_DATABASE;
    @Value("redis.key")
    private String REDIS_KEY;
//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterVo registerVo) {
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        // 校验参数
        if (StringUtils.isBlank(nickname) || !FormUtils.isMobile(mobile)
            || StringUtils.isBlank(password) || StringUtils.isBlank(code)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }

        // 校验验证码
        String checkCode = (String) redisService.get(REDIS_DATABASE + ":" + REDIS_KEY + ":" + mobile);
        if (!code.equals(checkCode)) {
            throw new CustomException(ResultCodeEnum.CODE_ERROR);
        }

        // 是否被注册
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        List<Member> memberList = baseMapper.selectList(queryWrapper);
        if (!memberList.isEmpty()){
            throw new CustomException(ResultCodeEnum.REGISTER_MOBLE_ERROR);
        }

        // 注册
        Member member = new Member();
        member.setNickname(nickname);
        member.setMobile(mobile);
        member.setPassword(MD5.encrypt(password));
        member.setDisabled(false);
        member.setAvatar("https://vcourse-file-1.oss-cn-hangzhou.aliyuncs.com/avatar/default/default.jpg");
        baseMapper.insert(member);
    }

    @Override
    public String login(LoginVo loginVo) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //校验参数
        if (StringUtils.isEmpty(mobile)
                || !FormUtils.isMobile(mobile)
                || StringUtils.isEmpty(password)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }

        //校验手机号
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        Member member = baseMapper.selectOne(queryWrapper);
        if(member == null){
            throw new CustomException(ResultCodeEnum.LOGIN_MOBILE_ERROR);
        }

        //校验密码
        if(!MD5.encrypt(password).equals(member.getPassword())){
            throw new CustomException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //检验用户是否被禁用
        if(member.getDisabled()){
            throw new CustomException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());
        return JwtUtils.getJwtToken(jwtInfo, 1800);
    }

//    @Override
//    public UserDetails loadUserByUsername(String username) {
//        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("mobile", username);
//        Member member = baseMapper.selectOne(queryWrapper);
//        if (member != null) {
//            return new MemberDetails(member);
//        }
//        throw new CustomException(ResultCodeEnum.LOGIN_PHONE_ERROR);
//    }

    @Override
    public MemberDto getMemberDtoByMemberId(String memberId) {
        Member member = baseMapper.selectById(memberId);
        MemberDto memberDto = new MemberDto();
        BeanUtils.copyProperties(member, memberDto);
        return memberDto;
    }

    @Override
    public int getCountRegistryNum(String day) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("gmt_create", day);
        return baseMapper.selectCount(memberQueryWrapper);
    }
}
